package com.sgb.kjwl.view.ui.activity.enterprise;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityNeedlistdetaulBinding;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.PointUtils;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.enterprise.NewNeedDataAdpater;
import com.sgb.kjwl.viewmodel.enterprise.NeedListDetailModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.Serializable;
import java.util.Date;

/**
 * 发布需求详情
 */
public class PublishNeedDataDateilActivity extends AppActivity {

    private NeedListDetailModel mViewModel;
    private ActivityNeedlistdetaulBinding mBinding;
    private NewNeedDataAdpater madpater;
    private boolean stopTabLayoutScroll = false;
    private boolean stopRecyclerViewScroll = false;
    private LinearLayoutManager mLinearLayoutManager;
    private int mIndex = 0;
    private Context mContext;

    public static void startactivity(Context mContext, String id) {
        Intent mIntent = new Intent();
        mIntent.setClass(mContext, PublishNeedDataDateilActivity.class);
        mIntent.putExtra("data", id);
        mContext.startActivity(mIntent);


    }


    @Override
    protected void initView() {
        super.initView();
        mContext = this;
        mViewModel = new ViewModelProvider(this).get(NeedListDetailModel.class);
        mViewModel.setMitemid(getIntent().getStringExtra("data"));

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_needlistdetaul);
        mBinding.setVariable(BR.needmodel, mViewModel);
        mBinding.setLifecycleOwner(this);

        init_recyclerView();
        init_tablayout();
        init_observe();
        init_lister();

        mViewModel.getDetails();


    }


    private void init_recyclerView(){
        madpater = new NewNeedDataAdpater(this);
        //不展示下架
        madpater.setShowxiajia(false);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mBinding.recyclerView.setLayoutManager(mLinearLayoutManager);
        mBinding.recyclerView.setAdapter(madpater);

    }

    private void init_tablayout(){
        for (String s : mViewModel.titleList) {
            mBinding.tabLayout.addTab(mBinding.tabLayout.newTab().setText(s));
        }

        mBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mIndex = tab.getPosition();
                if (mIndex != 0) {
                    scrollToTop();
                }

                int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
                int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
                //然后区分情况

                if (mIndex <= firstItem) {
                    //当要置顶的项在当前显示的第一个项的前面时
                    mBinding.recyclerView.scrollToPosition(mIndex);
                } else if (mIndex <= lastItem) {
                    //当要置顶的项已经在屏幕上显示时
                    int top = mBinding.recyclerView.getChildAt(mIndex - firstItem).getTop();
                    mBinding.recyclerView.scrollBy(0, top);
                } else {
                    //当要置顶的项在当前显示的最后一项的后面时
                    mBinding.recyclerView.scrollToPosition(mIndex);
                    //这里这个变量是用在RecyclerView滚动监听里面的
                }

                stopRecyclerViewScroll = true;
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    private void init_observe(){
        mViewModel.ShowLoading.observe(this, type -> {
            switch (type) {
                case 1:
                    DialogHelper.showProgressDialog(PublishNeedDataDateilActivity.this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelper.dismissProgressDialog();
                    break;
            }
        });
        mViewModel.Toast_until.observe(this, message -> {
            MToast.showLongToast(this, message);

        });


        mViewModel.date_detail.observe(this, data -> {
            madpater.setNeedDetail(data);//填充详情数据

            mBinding.coordinator.setVisibility(View.VISIBLE);
            mBinding.llBottom.setVisibility(View.VISIBLE);
            mViewModel.getsignuplist(data.id+"");
            if (data.getBudgetPrice() >-1) {
                mBinding.tvPrice.setText("￥" + PointUtils.price(data.getBudgetPrice()));
            } else {
                mBinding.tvPrice.setText("议价");
            }

            if("0".equals(data.getWhetherPublic())){
                if(System.currentTimeMillis()<data.getPublicityPeriod()){
                    mBinding.linEnd.setVisibility(View.VISIBLE);
                }else{
                    mBinding.linEnd.setVisibility(View.GONE);
                }

            }


            switch (data.getOfferStatus()) {
                case 1:
                    mBinding.tvDetailtype.setBackgroundResource(R.drawable.shape_needdetail_bjz);
                    mBinding.tvDetailtype.setTextColor(Color.parseColor("#5792FD"));
                    break;
                case 2:
                    mBinding.tvDetailtype.setBackgroundResource(R.drawable.shape_needtype_colorback);
                    mBinding.tvDetailtype.setTextColor(Color.parseColor("#666666"));
                    break;
                case 3:
                    mBinding.tvDetailtype.setBackgroundResource(R.drawable.shape_needetail_ysx);
                    mBinding.tvDetailtype.setTextColor(Color.parseColor("#C0C4CC"));
                    break;
            }


        });


        mViewModel.list_signup.observe(this,listdata->{
            madpater.setNeedDetailSignUpData(listdata);
        });
    }

    private void init_lister(){

        mBinding.tvQuxiao.setOnClickListener(view->{
            com.sgb.kjwl.utils.DialogHelper.showDialog(PublishNeedDataDateilActivity.this, "温馨提示", "确认取消该需求？", "确定", new DialogFunction() {
                @Override
                public void normalRoundDialog() {
                    mViewModel.updateType();
                }
            });

        });
        mBinding.tvChoice.setOnClickListener(view -> {
            if (mViewModel.date_detail.getValue().getOfferStatus() == 1) {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(PublishNeedDataDateilActivity.this);
                    return;
                }

                NeedSignUpListActivity.start(PublishNeedDataDateilActivity.this,mViewModel.date_detail.getValue().getId()+"");
            } else {
                Intent mintent = new Intent();
                switch (mViewModel.date_detail.getValue().requirementTypes) {
                    case 1:
                        mintent.setClass(PublishNeedDataDateilActivity.this, AddNeed_TrandActivity.class);
                        break;
                    case 2:
                        mintent.setClass(PublishNeedDataDateilActivity.this, AddNeed_PatentActivity.class);
                        break;
                    case 3:
                        mintent.setClass(PublishNeedDataDateilActivity.this, AddNeed_CopyRightActivity.class);
                        break;
                    case 5:
                        mintent.setClass(PublishNeedDataDateilActivity.this, AddNeed_ServiceActivity.class);
                        break;

                }
                mintent.putExtra("data", (Serializable) mViewModel.date_detail.getValue());
                mContext.startActivity(mintent);
            }
        });
    }


    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = mBinding.appBarLayout.getLayoutParams();
        CoordinatorLayout.Behavior behavior =
                ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = mBinding.tabLayout.getY();
            //注意传递负值
            appBarLayoutBehavior.setTopAndBottomOffset((int) -y);
        }

    }

}
